package cn.com.blink.day0521;


import org.junit.Test;

import javax.swing.*;
import java.awt.event.ActionListener;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.function.*;

/**
 * lambda表达式
 * 1.lambda表达式是一个匿名方法，其行为像数据一样传递
 * 2.lambda表达式的常见结构：Predicate<Integer> atLeast5 = x -> x > 5;
 * 3.函数接口：指仅具有单个抽象方法的接口，用来表示Lambda表达式的类型
 * Created by liuzh on 2017/5/21.
 */
public class LambdaTest {

    //如何辨别lambda表达式
    @Test
    public void test1() {
        Runnable noArguments = () -> System.out.println("无参数lambda实例");
        new Thread(noArguments).start();

        ActionListener oneArgument = event -> System.out.println("一个参数lambda实例");

        Runnable multiStatement = () -> {
            System.out.println("statement1");
            System.out.println("statement2");
        };

        BinaryOperator<Long> add = (x, y) -> x + y;//多参数

        BinaryOperator<Long> addExplict = (Long x, Long y) -> x + y;//显示声明参数类型
    }

    //函数接口
    @Test
    public void test2() {
        Predicate<Integer> atLeast5 = x -> x > 5;

        BinaryOperator<Long> add = (x, y) -> x + y;//多参数

        Consumer<Integer> integerConsumer = x -> System.out.println(x);

        Function<List<String>, Integer> listSize = arryList -> arryList.size();

        Supplier<String> integerSupplier = () -> "a";

        UnaryOperator<Boolean> booleanUnaryOperator = aBoolean -> !aBoolean;

    }

    //类型推断
    @Test
    public void test3() {
        Map<String, String> map = new HashMap<>();//菱形推断

        useHashMap(new HashMap<>());

//        BinaryOperator add = (x, y) -> x + y;//无泛型编译器不通过
    }


    private void useHashMap(Map<String, String> values) {
        values.forEach((s, s2) -> System.out.println(s + ":" + s2));
    }

    @Test
    public void execise1() {
        ThreadLocal<DateTimeFormatter> threadLocal = ThreadLocal.withInitial(() -> {
            DateTimeFormatter dateFormatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
            return dateFormatter;
        });
        LocalDateTime date = LocalDateTime.now();
        String text = date.format(threadLocal.get());
        System.out.println(text);
        System.out.println(threadLocal.get().format(date));
    }

    @Test
    public void execise2() {
        JButton button = new JButton();
        button.addActionListener(e -> System.out.println(e.getActionCommand()));

        DataCheck dataCheck = new DataCheck();
        System.out.println(dataCheck.check(100, value -> {
            return value.intValue() > 1000;
        }));
        System.out.println(dataCheck.check(100, value -> {
            return value.intValue() > 10;
        }));
    }
}

class DataCheck {
    boolean check(Integer o, Predicate<Integer> predicate) {
        return predicate.test(o);
    }
//重写后编译器不通过
//    boolean check(Integer o, IntPred predicate) {
//        return predicate.test(o);
//    }
}